<?php
/**
 * +--------------------------------------------------------------
 * | eLuoPHP
 * +--------------------------------------------------------------
 * | Copyright (c) 2013-2019 http://qxwoo.cn All rights reserved.
 * +--------------------------------------------------------------
 * | y139w [y139w@163.com]
 * +--------------------------------------------------------------
 * | URL地址处理类文件
 * +--------------------------------------------------------------
 */

namespace luo;


class Url
{

    /**
     * @var Request|null
     */
    private $request = null;

    /**
     * Url constructor.
     */
    public function __construct()
    {
        $this->request = Request::instance();
    }

    /**
     * @return Url
     */
    public static function instance(){

        return (new self());

    }

    /**
     * @param $url
     * @param array $param
     * @return string
     */
    public function build($url, Array $param = []){

        $url = implode('?', [
            $this->parseUrl($url),
            $this->parseParam($param)
        ]);
        $url = trim($url, '?');
        return $url;

    }

    /**
     * @param $url
     * @return string
     */
    private function parseUrl($url){

        $host = 'http://' . $this->request->server('HTTP_HOST');

        $root = $this->request->root();

        $url = explode('/',$url);

        $action = array_pop($url) ? : $this->request->action();
        $controller = array_pop($url) ? : $this->request->controller();
        $module = array_pop($url) ? : $this->request->module();

        $mca = implode('/', [$module, $controller, $action]);

        $host = '';
        $template = Config::get('template');
        $tplExt = $template['template_ext'] ?? '.html';
        $router = Router::instance()->get($mca);
        if($router){
            $mca = $router;
        }

        $urls = implode('', [$host, $root, $mca, $tplExt]);

        return $urls;

    }

    /**
     * @param array $param
     * @return array|string
     */
    private function parseParam(Array $param = []){

        //$param = array_merge($param, $this->request->get());
        $param = http_build_query($param);
        return $param;

    }

}